import React from 'react';
import { useRef, forwardRef, useImperativeHandle, useState, useEffect } from 'react';
import { QueryTable } from 'sula';
import type { QueryTableProps } from 'sula';
import isUndfined from 'lodash/isUndefined';
import styles from './styles.less';

declare const defaultProps: {
  formProps: Record<string, unknown>;
  tableProps: Record<string, unknown>;
  fields: never[];
  columns: never[];
  autoInit: boolean;
  beforeSearch?: (params: any) => void;
  afterSearch?: (data: PaginationData<any>) => void;
  ref: any;
};
export type MQueryTableProps = QueryTableProps & Partial<typeof defaultProps>;

const replaceFieldsType = (fields: any) => {
  if (!(fields && Array.isArray(fields))) {
    return [];
  }
  return fields.map((item: any) => {
    if (item.field) {
      if (item.field.type === 'input') {
        // eslint-disable-next-line no-param-reassign
        item.field.type = 'enhancedInput';
      }
      if (
        ['enhancedInput', 'formatterInput'].includes(item.field.type) &&
        isUndfined(item.field.props?.pressEnterTriggerSubmit)
      ) {
        // eslint-disable-next-line no-param-reassign
        item.field.props = { ...item.field.props, pressEnterTriggerSubmit: true };
      }
    }
    return item;
  });
};

const MQueryTable: React.FC<MQueryTableProps> = forwardRef(
  (
    {
      tableProps,
      fields,
      initialValues: initialValuesProps,
      remoteDataSource,
      beforeSearch,
      afterSearch,
      ...rest
    },
    ref: any,
  ) => {
    const queryTableRef = useRef<any>();
    useImperativeHandle(ref, () => ({
      ...queryTableRef.current,
    }));

    const [formFields, setFormFields] = useState<any>(replaceFieldsType(fields));
    useEffect(() => {
      setFormFields(replaceFieldsType(fields));
    }, [fields]);
    return (
      <div className={styles.normalTalbe}>
        <QueryTable
          layout="horizontal"
          itemLayout={{ cols: 4 }}
          visibleFieldsCount={15} // 最多显示15个搜索项，其他溢出隐藏
          formProps={{
            colon: false,
            onFinish: (value) => {
              const { tableRef } = queryTableRef.current;
              const { setFilters, refreshTable } = tableRef.current;
              setFilters(value);
              refreshTable();
            },
          }}
          fields={formFields}
          initialValues={initialValuesProps}
          remoteDataSource={(() => {
            if (remoteDataSource) {
              const newRemoteDataSource = { ...remoteDataSource };
              const oldConvertParams = newRemoteDataSource.convertParams;
              const oldConverter = newRemoteDataSource.converter;
              newRemoteDataSource.convertParams = (data) => {
                if (beforeSearch) {
                  beforeSearch(data.params);
                }
                if (typeof oldConvertParams === 'function') {
                  return oldConvertParams(data);
                }
                return data.params;
              };

              newRemoteDataSource.converter = (arg: any) => {
                const { data } = arg;
                setTimeout(() => {
                  if (afterSearch) {
                    afterSearch(data);
                  }
                }, 200);
                if (typeof oldConverter === 'function') {
                  return oldConverter(arg);
                }
                return data;
              };
              return newRemoteDataSource;
            }
            return undefined;
          })()}
          tableProps={{
            size: 'small',
            scroll: { x: 1200 },
            initialPaging: {
              pagination: {
                pageSize: 50,
                pageSizeOptions: ['10', '50', '200', '1000', '2000'],
                showSizeChanger: true,
                showQuickJumper: true,
                showTotal: (total, range) => `第 ${range[0]}-${range[1]} 条/总共 ${total} 条`,
              },
            },
            ...tableProps,
          }}
          rowSelection={{ columnWidth: 50 }}
          {...rest}
          ref={queryTableRef as any}
        />
      </div>
    );
  },
);

export default MQueryTable;
